package com.cam.framework.crud;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class CrudTreeService<DTO extends CrudTreeDTO<DTO>, Entity extends CrudTreeEntity, Mapper extends CrudTreeMapper<DTO, Entity>> extends CrudService<DTO, Entity, Mapper> {

    public Mapper mapper;

    public CrudTreeService(Mapper mapper) {
        this.mapper = mapper;
    }

    public List<DTO> treeFormat(List<DTO> dtoList, String rootId, Boolean onlyRoot) {
        List<DTO> result = new ArrayList<>();
        // 将元素id作为key，将entity作为value，保存所有元素，用于循环查找父元素
        Map<String, DTO> dtoMap = new HashMap<>();
        // 保存第一次循环未匹配到父元素的元素，用于第二次巡查匹配
        List<DTO> unmatchedList = new ArrayList<>();

        for (DTO eachDTO : dtoList) {
            if (eachDTO.getId().equals(rootId)) {
                result.add(eachDTO);
            } else {
                unmatchedList.add(eachDTO);
            }
            dtoMap.put(eachDTO.getId(), eachDTO);
        }

        for (DTO eachDTO : unmatchedList) {
            String parentId = eachDTO.getParentId();
            if (dtoMap.containsKey(parentId)) {
                dtoMap.get(parentId).getChildren().add(eachDTO);
            } else if (!onlyRoot) {
                result.add(eachDTO);
            }
        }

        return result;
    }

    @Override
    public boolean saveOrUpdate(Entity entity) {
        return super.saveOrUpdate(entity);
    }
}
